package com.lan.iot.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lan.iot.R;
import com.lan.iot.RAdapterdev;
import com.lan.iot.utils.JsonUtil;
import com.lan.iot.utils.OkHttpRequestUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import cn.com.newland.nle_sdk.requestEntity.SignIn;
import cn.com.newland.nle_sdk.responseEntity.User;
import cn.com.newland.nle_sdk.responseEntity.base.BaseResponseEntity;
import cn.com.newland.nle_sdk.util.NCallBack;
import cn.com.newland.nle_sdk.util.NetWorkBusiness;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class VPFdev extends VPFragment {
    View.OnClickListener cl=new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int id=view.getId();
            switch (id){
                case R.id.zero:
                    alarmservice(0);
                    break;
                case R.id.one:
                    alarmservice(1);

                    break;
                case R.id.two:
                    alarmservice(2);

                    break;
                case R.id.three:
                    alarmservice(3);

                    break;
                case R.id.four:
                    alarmservice(4);

                    break;
                case R.id.five:
                    alarmservice(5);

                    break;
            }
        }
    };
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "img";
    public static VPFdev newInstance(String title, int img) {
        VPFdev fragment = new VPFdev();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, title);
        args.putInt(ARG_PARAM2, img);
        fragment.setArguments(args);
        return fragment;
    }

    String token;
    NetWorkBusiness netWorkBusiness;

    private void init() {
        NetWorkBusiness netWorkBusiness2 = new NetWorkBusiness("", "http://www.nlecloud.com/");
        netWorkBusiness2.signIn(new SignIn("17680316790", "1234567890"), new NCallBack<BaseResponseEntity<User>>(getContext()) {
            @Override
            protected void onResponse(BaseResponseEntity<User> response) {
                netWorkBusiness = new NetWorkBusiness(response.getResultObj().getAccessToken(), "http://www.nlecloud.com/");
                token = response.getResultObj().getAccessToken();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        NlecloudUtil nlecloudUtil=new NlecloudUtil();
//                        nlecloudUtil.gainDevices("596248", token, new NlecloudResponse<List<SensorInfoEntity>>() {
//                            @Override
//                            public void callBack(ResultEntity<List<SensorInfoEntity>> resultEntity) {
//                                List<SensorInfoEntity> resultObj = resultEntity.getResultObj();
//                            }
//                        });
                    }
                }).start();
            }
        });
    }

    private void controlDevice(String deviceId, String apiTag, String data) {
        System.out.println("6");
        //发出网络请求
        String SENSOR_DATA_ALL = "http://api.nlecloud.com/Cmds";
        try {
            Map<String, String> valmap = new HashMap<>();
            valmap.put("deviceId", deviceId);
            valmap.put("apiTag", apiTag);
            Response access = OkHttpRequestUtil.postAccess(SENSOR_DATA_ALL, valmap, data, token);
            if (access.isSuccessful()) {
                ResponseBody body = access.body();
                Map map = JsonUtil.toMap(body.string());
                Double status = (double) map.get("Status");
                Message message = new Message();
                if (status == null || status.intValue() != 0.0) {
                    message.arg1 = 0;
                } else {
                    message.arg1 = 1;
                }
                message.obj = map.get("Msg");
                message.what = 0x01;
                handler.sendMessage(message);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0x01:
                    int status = msg.arg1;
                    String msgText = "";
                    if (status == 0) {
                        msgText = "控制失败:" + msg.obj;
                    } else if (status == 1) {
                        msgText = "控制成功:" + msg.obj;
                    }
                    Toast.makeText(getContext(), msgText, Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_v_p_dev, container, false);
        Bundle argument = getArguments();
        final RAdapterdev mAdapter;
        RecyclerView mRecyclerView;
        mRecyclerView = view.findViewById(R.id.recycler_view);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2, LinearLayoutManager.VERTICAL, false);

        mRecyclerView.setLayoutManager(gridLayoutManager);
        mAdapter = new RAdapterdev(getContext());
        mRecyclerView.setAdapter(mAdapter);

        /**
         * 设置网格布局每个item的间距
         */
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                //item1距离底部的距离
                outRect.bottom = 30;
                //item距离左侧的距离
                outRect.left = 30;
            }
        });
        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter_a = new IntentFilter();
        intentFilter_a.addAction("android.intent.action.CART_BROADCAST_adddev");
        BroadcastReceiver mItemViewListClickReceiver_dev = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int type = intent.getIntExtra("devtype", 0);
                String name = intent.getStringExtra("mdata");
                mAdapter.add_dev(name, type);
            }
        };
        broadcastManager.registerReceiver(mItemViewListClickReceiver_dev, intentFilter_a);
//        IntentFilter intentFilter_b = new IntentFilter();
//        intentFilter_b.addAction("android.intent.action.CART_BROADCAST_jiandev");
//        BroadcastReceiver mItemViewListClickReceiver_jiandev = new BroadcastReceiver() {
//            @Override
//            public void onReceive(Context context, Intent intent){
//                int type=intent.getIntExtra("devtype",0);
//                String name=intent.getStringExtra("mdata");
//                mAdapter.add_dev(name,type);
//            }
//        };
//        broadcastManager.registerReceiver(mItemViewListClickReceiver_jiandev, intentFilter_b);
        init();

        Button btn = view.findViewById(R.id.on);
        Button btn1 = view.findViewById(R.id.off);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAdapter.on();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        controlDevice("638233","Yijian","1");
                        //airconditionControl();
                    }
                }).start();
            }
        });
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAdapter.off();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        controlDevice("638233","Yijian","0");
                        //airconditionControl();
                    }
                }).start();
            }
        });
        Button btnceshi=view.findViewById(R.id.zero);
        Button one=view.findViewById(R.id.one);
        Button two=view.findViewById(R.id.two);
        Button three=view.findViewById(R.id.three);
        Button four=view.findViewById(R.id.four);
        Button five=view.findViewById(R.id.five);
        btnceshi.setOnClickListener(cl);
        one.setOnClickListener(cl);
        two.setOnClickListener(cl);
        three.setOnClickListener(cl);
        four.setOnClickListener(cl);
        five.setOnClickListener(cl);

//        ImageView iv = view.findViewById(R.id.iv);
//        iv.setImageResource(argument.getInt(ARG_PARAM2,R.drawable.ji1));
        return view;
    }
    public void alarmservice(final int i){
        new Thread(new Runnable() {
            @Override
            public void run() {
                controlDevice("638233","time_task",i+"");
                //airconditionControl();
            }
        }).start();
    }
}
